import 'package:flutter/material.dart';
import 'package:xh_danmu/xh_danmu.dart';
import 'custom_danmu_components.dart';

/// 弹幕输入组件示例
///
/// 这是一个独立的输入组件，展示如何使用Stream向弹幕组件发送数据
class DanmuInputWidget extends StatefulWidget {
  /// 弹幕流控制器
  final XhDanmuStreamController streamController;

  /// 提示文本
  final String? hintText;

  /// 发送完成回调
  final VoidCallback? onSent;

  /// 文本样式
  final TextStyle? textStyle;

  /// 输入框装饰
  final InputDecoration? inputDecoration;

  /// 容器装饰
  final BoxDecoration? containerDecoration;

  const DanmuInputWidget({
    super.key,
    required this.streamController,
    this.hintText,
    this.onSent,
    this.textStyle,
    this.inputDecoration,
    this.containerDecoration,
  });

  @override
  State<DanmuInputWidget> createState() => _DanmuInputWidgetState();
}

class _DanmuInputWidgetState extends State<DanmuInputWidget> {
  final TextEditingController _textController = TextEditingController();
  final FocusNode _focusNode = FocusNode();

  @override
  void dispose() {
    _textController.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  void _sendDanmu() {
    final text = _textController.text.trim();
    if (text.isNotEmpty) {
      // 通过Stream发送弹幕数据（带点击事件）
      final component = SimpleTextDanmuComponent(
        id: 'input_${DateTime.now().millisecondsSinceEpoch}',
        text: text,
        color: _getRandomColor(),
        clickable: true,
        extra: {
          'interactive': true,
        },
      );
      widget.streamController.add(XhDanmuData(
        id: component.id,
        component: component,
      ));
      _textController.clear();
      widget.onSent?.call();
    }
  }

  Color _getRandomColor() {
    final colors = [
      Colors.white,
      Colors.red,
      Colors.green,
      Colors.blue,
      Colors.orange,
      Colors.purple,
      Colors.cyan,
      Colors.pink,
    ];
    return colors[DateTime.now().millisecond % colors.length];
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: widget.containerDecoration ??
          BoxDecoration(
            color: Colors.black.withOpacity(0.8),
            borderRadius: BorderRadius.circular(8),
          ),
      child: Row(
        children: [
          Expanded(
            child: TextField(
              controller: _textController,
              focusNode: _focusNode,
              style: widget.textStyle ?? const TextStyle(color: Colors.white),
              decoration: widget.inputDecoration ??
                  InputDecoration(
                    hintText: widget.hintText ?? '输入弹幕内容...',
                    hintStyle: const TextStyle(color: Colors.white54),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(20),
                      borderSide: const BorderSide(color: Colors.white30),
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(20),
                      borderSide: const BorderSide(color: Colors.white30),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(20),
                      borderSide: const BorderSide(color: Colors.blue),
                    ),
                    contentPadding: const EdgeInsets.symmetric(
                      horizontal: 16,
                      vertical: 12,
                    ),
                    filled: true,
                    fillColor: Colors.white.withOpacity(0.1),
                  ),
              onSubmitted: (_) => _sendDanmu(),
              textInputAction: TextInputAction.send,
            ),
          ),
          const SizedBox(width: 8),
          ElevatedButton(
            onPressed: _sendDanmu,
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.blue,
              foregroundColor: Colors.white,
              shape: const CircleBorder(),
              padding: const EdgeInsets.all(12),
            ),
            child: const Icon(Icons.send, size: 20),
          ),
        ],
      ),
    );
  }
}

/// 弹幕控制面板组件
class DanmuControlWidget extends StatelessWidget {
  final XhDanmuController controller;
  final XhDanmuStreamController streamController;

  const DanmuControlWidget({
    super.key,
    required this.controller,
    required this.streamController,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.black.withOpacity(0.8),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        children: [
          const Text(
            '弹幕控制',
            style: TextStyle(
              color: Colors.white,
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 12),
          Wrap(
            spacing: 8,
            runSpacing: 8,
            alignment: WrapAlignment.center,
            children: [
              // 播放/暂停按钮
              ElevatedButton.icon(
                onPressed: () {
                  if (controller.isPlaying) {
                    controller.pauseAnimation();
                  } else {
                    controller.startAnimation();
                  }
                },
                icon: Icon(
                  controller.isPlaying ? Icons.pause : Icons.play_arrow,
                  size: 16,
                ),
                label: Text(
                  controller.isPlaying ? '暂停' : '播放',
                  style: const TextStyle(fontSize: 12),
                ),
                style: ElevatedButton.styleFrom(
                  backgroundColor: controller.isPlaying ? Colors.orange : Colors.green,
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                ),
              ),

              // 清空按钮
              ElevatedButton.icon(
                onPressed: controller.clearAllDanmu,
                icon: const Icon(Icons.clear_all, size: 16),
                label: const Text('清空', style: TextStyle(fontSize: 12)),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.red,
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                ),
              ),

              // 测试按钮
              ElevatedButton.icon(
                onPressed: () => _sendTestData(),
                icon: const Icon(Icons.send, size: 16),
                label: const Text('测试', style: TextStyle(fontSize: 12)),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.blue,
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                ),
              ),

              // 批量测试按钮
              ElevatedButton.icon(
                onPressed: () => _sendBatchData(),
                icon: const Icon(Icons.burst_mode, size: 16),
                label: const Text('批量', style: TextStyle(fontSize: 12)),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.purple,
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  void _sendTestData() {
    final testTexts = [
      '这是通过Stream发送的弹幕',
      '数据流传输正常',
      'Stream控制器工作良好',
      '弹幕数据源测试',
      '外部数据接入成功！',
    ];

    final randomText = testTexts[DateTime.now().millisecond % testTexts.length];
    final component = SimpleTextDanmuComponent(
      id: 'test_${DateTime.now().millisecondsSinceEpoch}',
      text: randomText,
      color: Colors.cyan,
      fontSize: 16.0,
      clickable: true,
      extra: {
        'source': 'test_button',
      },
    );
    streamController.addComponent(component);
  }

  void _sendBatchData() {
    final batchData = [
      XhDanmuData(
        id: 'batch_1',
        component: SimpleTextDanmuComponent(
          id: 'batch_1',
          text: '批量数据1',
          color: Colors.red,
          fontSize: 18.0,
          clickable: true,
          extra: {'batch': true},
        ),
      ),
      XhDanmuData(
        id: 'batch_2',
        component: SimpleTextDanmuComponent(
          id: 'batch_2',
          text: '批量数据2',
          color: Colors.green,
          fontSize: 16.0,
          clickable: true,
          extra: {'batch': true},
        ),
      ),
      XhDanmuData(
        id: 'batch_3',
        component: SimpleTextDanmuComponent(
          id: 'batch_3',
          text: '批量数据3',
          color: Colors.blue,
          fontSize: 20.0,
          clickable: true,
          extra: {'batch': true},
        ),
      ),
    ];

    streamController.addAll(batchData);
  }
}

/// WebSocket 模拟组件
class WebSocketSimulatorWidget extends StatefulWidget {
  final XhDanmuStreamController streamController;

  const WebSocketSimulatorWidget({
    super.key,
    required this.streamController,
  });

  @override
  State<WebSocketSimulatorWidget> createState() => _WebSocketSimulatorWidgetState();
}

class _WebSocketSimulatorWidgetState extends State<WebSocketSimulatorWidget> {
  XhDanmuTimerSource? _timerSource;
  bool _isRunning = false;

  @override
  void dispose() {
    // 在dispose中不调用setState，直接清理资源
    _timerSource?.stop();
    _timerSource = null;
    super.dispose();
  }

  void _startSimulation() {
    if (_isRunning) return;

    _timerSource = XhDanmuTimerSource(
      interval: const Duration(seconds: 2),
      texts: [
        '模拟WebSocket消息1',
        '服务器推送弹幕',
        '实时数据流',
        '远程弹幕数据',
        '网络消息接收',
      ],
    );

    // 连接到弹幕流
    widget.streamController.stream.listen((data) {
      // 这里可以添加额外的处理逻辑
    });

    // 将定时器数据源的流连接到主流控制器
    _timerSource!.stream.listen((data) {
      widget.streamController.add(data);
    });

    _timerSource!.start();

    if (mounted) {
      setState(() {
        _isRunning = true;
      });
    }
  }

  void _stopSimulation() {
    _timerSource?.stop();
    _timerSource = null;

    // 检查Widget是否仍然mounted
    if (mounted) {
      setState(() {
        _isRunning = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.green.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.green.withOpacity(0.3)),
      ),
      child: Column(
        children: [
          const Text(
            'WebSocket 模拟器',
            style: TextStyle(
              color: Colors.white,
              fontSize: 14,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 8),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              ElevatedButton(
                onPressed: _isRunning ? null : _startSimulation,
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.green,
                  foregroundColor: Colors.white,
                ),
                child: const Text('开始模拟', style: TextStyle(fontSize: 12)),
              ),
              ElevatedButton(
                onPressed: _isRunning ? _stopSimulation : null,
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.red,
                  foregroundColor: Colors.white,
                ),
                child: const Text('停止模拟', style: TextStyle(fontSize: 12)),
              ),
            ],
          ),
          const SizedBox(height: 8),
          Text(
            _isRunning ? '模拟中...' : '已停止',
            style: TextStyle(
              color: _isRunning ? Colors.green : Colors.grey,
              fontSize: 12,
            ),
          ),
        ],
      ),
    );
  }
}
